/**
 * 主页JS,searchSize:搜索历史记录最大的条数
 */
let ventPageNo = 1, ventPageSize = 15,searchSize = 10,ventTotalPage = 0,isZh = false,
	selectCityCode = '',ventTypeArr = [];
$(function() {
	initTopVent();
	initVentCity();
	setMyHeader();
    listPageVent(ventPageNo,ventPageSize);
	//点击页面
	$(document).click(function () {
		$('.hide-info,.search-city-container').hide();
		//如果点击的不是搜索input，则隐藏历史记录
		if (this.activeElement.id != 'searchVentKey'){
			$('.search-history').hide();
		}
	});
	let cityKeyId = 'searchCityKey';
	//搜索城市
	$('#' + cityKeyId).keyup(function () {
		let searchKey = this.value;
		if (!isZh && !isNull(searchKey)) {
			window.setTimeout(function () {
				if (searchKey == V(cityKeyId)) {
					listAllCities(V(cityKeyId));
				}
			}, 500);
		}
		if (isNull(searchKey)) {
			$('.search-city-container').hide();
		}
	});
	let iptSearchKey = I(cityKeyId);
	addEvent(iptSearchKey, 'compositionstart', function (e) {
		e = e || window.event;
		if (isZh && V(cityKeyId)) {
			listAllCities(V(cityKeyId));
		}
		isZh = true;
	});
	addEvent(iptSearchKey, 'compositionend', function (e) {
		e = e || window.event;
		if (isZh && V(cityKeyId)) {
			listAllCities(V(cityKeyId));
		}
		isZh = false;
	});
	let searchVentKey = $('#searchVentKey'),searchUl = $('.search-history ul');
	//搜索框获得焦点
	searchVentKey.focus(function () {
		let searchHistoryArray = localStorage.getItem('searchHistory');
		if (isNull(searchHistoryArray) || searchHistoryArray.length < 1) {
			return;
		}
        searchHistoryArray = JSON.parse(searchHistoryArray);
		searchUl.empty();
        for (let i = 0; i < searchHistoryArray.length; i++) {
            if (!isNull(searchHistoryArray[i])) {
				searchUl.append('<li>' + searchHistoryArray[i] + '</li>');
            }
        }
        $('.search-history').show();
	});
	$(".search-history").on("click", "li", function () {
		searchVentKey.val($(this).text());
	});
	//执行搜索，并将搜索记录添加到搜索历史记录中
	$('#btnSearchKey').click(function() {
		//将搜索历史记录存入localStorage中
		let searchHistoryStr = localStorage.getItem('searchHistory'), keyValue = searchVentKey.val();
		if (isNull(keyValue)) {
			listPageVent(1,ventPageSize);
            return;
		}
		let searchStorageArray = isNull(searchHistoryStr) ? [] : JSON.parse(searchHistoryStr);
		//如果搜索历史中不存在，则添加到历史记录中，否则不添加
		if (searchStorageArray.indexOf(keyValue) < 0) {
			searchStorageArray.unshift(keyValue);
		}
		let searchLen = searchStorageArray.length;
		//如果searchStorageArray中的元素个数超过searchSize，则删除最后1个元素
		if (searchLen > searchSize){
			searchStorageArray.splice(searchLen - 1,1);
		}
		listPageVent(1,ventPageSize);
        localStorage.setItem('searchHistory', JSON.stringify(searchStorageArray));
	});
});

/**
 * 添加事件
 * @param el 要添加事件的元素
 * @param type 事件类型
 * @param fn 事件要执行的函数
 */
function addEvent(el, type, fn) {
	if (el.addEventListener) {
		el.addEventListener(type, fn, false);
	} else {
		el.attachEvent('on' + type, fn);
	}
}

/**
 * 获取城市数据
 * @param cityPinYinOrName 城市拼音首字母或名字
 */
function listAllCities(cityPinYinOrName) {
	if (isNull(cityPinYinOrName)) {
		return;
	}
	let isHaveZh = false, isHaveEn = false, isLoad = true,//是否需要加载
		fullPinyin = '', sCityName = '',pinYinNameArray = cityPinYinOrName.split('');
	for (let g = 0; g < pinYinNameArray.length; g ++) {
		//如果不是汉字，也不是字母，则不加载
		let zhReg = /[\u4e00-\u9fa5]/g, enReg = /[a-zA-Z]/g;
		let isZh = !zhReg.test(pinYinNameArray[g]), isEn = !enReg.test(pinYinNameArray[g]);
		if (isZh && isEn) {
			isLoad = false;
			break;
		} else if (isZh) {
			isHaveZh = true;
		} else if (isEn) {
			isHaveEn = true;
		}
		if (isHaveZh && isHaveEn) {
			isLoad = false;
			break;
		}
	}
	if (!isLoad) {
		appendSearchNoCity();
		return;
	}
	if (!isHaveZh && isHaveEn) {
		sCityName = cityPinYinOrName;
	} else {
		fullPinyin = cityPinYinOrName.toUpperCase();
	}
	$.ajax({
		type: "POST",
		url: '/ventIndex/listAllCities',
		data: {fullPinyin: fullPinyin, cityName: sCityName},
		dataType: 'json',
		async: false,
		success: function (cityArr) {
			if (cityArr == null || cityArr.length < 1) {
				appendSearchNoCity();
				return;
			}
			let cityAs = [];
			for (let g = 0; g < cityArr.length; g ++){
				let cityObj = cityArr[g];
				cityAs.push('<a id="' + cityObj.cityCode + '">' + cityObj.cityName + '</a>');
			}
			$('.search-city-container').empty().append(cityAs.join('')).show();
			$('.search-city-container a').click(function () {
				searchCity(this);
			});
		},
		error: function () {
			alert('当前系统繁忙,请稍后再试');
		}
	});
}
/**
 * 初始化页面顶部的吐槽类型及各标签的位置
 */
function initTopVent(){
	//获取职业类型
	ventTypeArr = getDictionaries(52);
	//宽度：全民吐槽+搜索框+我要吐槽按钮和我的头像+（热门+最新）+更多
	let otherWidth = 126 + 238 + 174 + 64 * 2 + 84,bodyWidth = $('body').width();
	//顶上吐槽人身份的a标签的宽度计算公式，bodyWidth * 0.1：左右两边共留出10%的空白
	let surplusWidth = bodyWidth - otherWidth - (bodyWidth * 0.1) - 80, vtLen = ventTypeArr.length,moreVentArr = [],
		topVentArr = ['<li class="active"><a id="hot">热门</a></li>','<li><a id="new">最新</a></li>'];
	for (let g = 0; g < vtLen; g ++){
		let vtObj = ventTypeArr[g],ventType = vtObj.dicName;
		let ventAWidth = getVentAWidth(ventType),aStr = '<li><a id="' + vtObj.id + '">' + ventType + '</a></li>';
		//如果吐槽类型A标签的宽度 < 剩余宽度(body宽度-otherWidth之后的宽度)
		if (ventAWidth < surplusWidth){
			topVentArr.push(aStr);
			surplusWidth -= ventAWidth;
		} else {
			moreVentArr.push(aStr);
		}
	}
	topVentArr.push('<li><a class="more">更多<span style="letter-spacing: 0;">>></span></a></li>');
	$('#topVentList').empty().append(topVentArr.join(''));
	$('.occupation ul').empty().append(moreVentArr.join(''));
	setMoreMyselfPosition();
	//重新添加鼠标移上监听事件
	$('.more').mouseover(function () {
		$('.occupation').show();
	});
	$('.myself-header').mouseover(function () {
		$('.myself-menu').show();
	});
	let ventTypeLi = $('.vent-type li');
	ventTypeLi.click(function () {
	    //如果当前是已选择的或“更多”
	    if ($(this).hasClass('active') || $(this).children('a').hasClass('more')){
	        return;
        }
		ventTypeLi.removeClass('active');
		$(this).addClass('active');
        listPageVent(1,ventPageSize);
	});
}
//实时监听窗口大小变化
window.onresize = function () {
	initTopVent();
};
function appendSearchNoCity() {
	$('.search-city-container').empty().html('<label style="color: #e51400;font-weight: bolder;">没找到对应的城市</label>').show();
}
/**
 * 初始化吐槽的热门城市数据
 */
function initVentCity() {
	let hotCityList = getDictionaries(39),hotCityArr = [];
	for (let i = 0; i < hotCityList.length; i ++){
		let hotCity = hotCityList[i];
		hotCityArr.push('<a id="' + hotCity.dicCode + '">' + hotCity.dicName + '</a>');
	}
	$('.hot-city').append(hotCityArr.join(''));
	let hotCityA = $('.hot-city a');
	hotCityA.click(function () {
		let isSelectCity = $(this).hasClass('select-city');
		hotCityA.removeClass('select-city');
		selectCityCode = this.id;
		if (isSelectCity){
			selectCityCode = '';
		} else {
			$(this).addClass('select-city');
		}
		listPageVent(1,ventPageSize);
	});
}

/**
 * 选中搜索的城市
 * @param scObj 选择的城市对象
 */
function searchCity(scObj) {
	$('.hot-city a').removeClass('select-city').each(function () {
		if (this.id == scObj.id){
			$(this).addClass('select-city');
			return;
		}
	});
	$('#searchCityKey').val($(scObj).text());
	selectCityCode = scObj.id;
	listPageVent(1,ventPageSize);
}
/**
 * 获取吐槽类型A标签的宽度
 * @param ventType 吐槽类型
 */
function getVentAWidth(ventType) {
	let wordWidth = 17,marginLeft = 6, marginRight = 12,letterSpacing = 6,ventLen = ventType.length;
	return wordWidth * ventLen + letterSpacing * ventLen + marginLeft + marginRight;
}

/**
 * 设置页面顶部吐槽职业类型“更多”和“我的”标签的位置
 */
function setMoreMyselfPosition() {
	//获取more元素距离浏览器左边的距离
	let moreLeft = getLeft('more');
	$('.occupation').css('left', (moreLeft - 1) + 'px');
    //页面加载完后过600毫秒才能获取到$('.myself-header').offset().left值
	setTimeout(function () {
        $('.myself-menu').css('left', ($('.myself-header').offset().left - 90) + 'px');
		$('.search-history').css('left', (getLeft('search') + 6) + 'px');
    },600);
}
function getLeft(className) {
	return getRect(className).left;
}
function getRect(className) {
	return document.getElementsByClassName(className)[0].getBoundingClientRect();
}
/**
 * 加载吐槽数据集合
 * @param currentPage  当前面码
 * @param pageSize   每页显示记录数
 */
function listPageVent(currentPage, pageSize) {
	$('.page-mask,.loading').show();
	$.ajax({
		type: 'post',
		url: 'ventIndex/listIndexPageVent',
		dataType: 'json',
		timeout: 30000,
		data: {
            occupationId: $('.vent-type .active a').attr('id'),
			cityCode: selectCityCode,
			pageNo: currentPage,
			pageSize: pageSize,
			searchKey: $('#searchVentKey').val()
		},
		success: function(pageVent) {
            loadVentList(currentPage, pageSize, pageVent);
		},
		error: function () {
			hideMaskLoading();
			alert('系统太忙了，请稍候再试！')
		}
	});
}

/**
 * 加载吐槽数据列表
 * @param currentPage 当前页号
 * @param pageSize 每页显示的订单数
 * @param pageVent 吐槽分页数据
 */
function loadVentList(currentPage, pageSize,pageVent) {
    let ventArray = pageVent.list,ventListDiv = $('#ventList'),paginate = $('.wp-paginate');
    ventListDiv.children().remove();
    if (ventArray != null && ventArray.length > 0) {
        //服务订单数据
        let appendArr = [],ventListSize = ventArray.length;
        for (let s = 0; s < ventListSize; s ++) {
            appendArr.push(getVentHtml(ventArray[s]));
        }
        ventListDiv.append(appendArr.join('')).show();
        //添加分页工具栏
        paginate.children().remove();
        //总记录数,总页数
        ventTotalPage = parseInt(pageVent.pages);

        let ellipsisLi = '<li class="page-ellipsis">…</li>',
            pageNums = pageVent.navigatepageNums, aHref = 'href="javascript:void(0)"';
        let firstClass = 'first-page', previousClass = 'previous-page', isHave = '';
        //如果没有上一页
        if (!pageVent.hasPreviousPage) {
            firstClass = 'no-first';
            previousClass = 'no-previous';
            isHave = 'no-have';
        }
        let appendStr = '<li title="第一页" class="' + firstClass + '"><a ' + aHref + ' class="first ' + isHave + '"></a></li>' +
            '<li title="上一页" class="' + previousClass + '"><a ' + aHref + ' class="previous ' + isHave + '"></a></li>';
        if (pageNums[0] > 1){
            appendStr += ellipsisLi;
        }
        if (ventTotalPage > 0) {
            //页面要显示的页数集合
            for (let g = 0; g < pageNums.length; g++) {
                let currentClass = pageNums[g] == currentPage ? 'current' : 'have';
                appendStr += '<li><a ' + aHref + ' class="page ' + currentClass + '">' + pageNums[g] + '</a></li>';
            }
        }
        if (pageNums[pageNums.length - 1] < pageVent.pages){
            appendStr += ellipsisLi;
        }
        let nextClass = 'next-page', lastClass = 'last-page';
        isHave = '';
        //如果没有下一页
        if (!pageVent.hasNextPage){
            nextClass = 'no-next';
            lastClass = 'no-last';
            isHave = 'no-have';
        }
        appendStr += '<li title="下一页" class="' + nextClass + '"><a ' + aHref + ' class="next ' + isHave + '"></a></li>' +
            '<li title="最后一页" class="' + lastClass + '"><a ' + aHref + ' class="last ' + isHave + '"></a></li>';
        paginate.append(appendStr);
    } else {
        ventListDiv.append('<span style="fonts-size: 18px;">没有找到吐槽信息，要不换个条件试试？</span>');
    }

    //分页数字点击事件
    $(".wp-paginate a").click(function() {
        let className = this.className;
        //如果class不包含no-have，并且不是当前页
        if (className.indexOf('no-have') == -1 && parseInt(this.innerText) != currentPage) {
            if (className.indexOf('first') > -1) {
                currentPage = 1;
            } else if (className.indexOf('previous') > -1) {
                currentPage = currentPage > 1 ? currentPage - 1 : 1;
            } else if (className.indexOf('next') > -1) {
                currentPage = currentPage < ventTotalPage ? currentPage + 1 : ventTotalPage;
            } else if (className.indexOf('last') > -1) {
                currentPage = ventTotalPage;
            } else {
                currentPage = parseInt(this.innerText);
            }
            listPageVent(currentPage, pageSize);
        }
    });
    //重新设置标题和内容的宽度
    setTitleContentWidth();
    //隐藏加载图片
    hideMaskLoading();
    $('.vent-obj a').click(function () {
        readTotalAddOne($(this).attr('href').split('?')[1]);
    });
}
/**
 * 隐藏遮罩层和加载图片
 */
function hideMaskLoading() {
	$('.page-mask,.loading').hide();
}
/**
 * 设置标题和内容的宽度
 */
function setTitleContentWidth(){
    $('.vent-obj strong,.vent-obj .content').css('width',($('.vent-obj').width() - 94) + 'px');
}

/**
 * 获取吐槽html
 * @returns {string} 吐槽html
 */
function getVentHtml(v) {
	let aOrSpan = v.isAnonymous == '1' ? 'span' : 'a';
	return '<div class="vent-obj">' +
        '<a target="_blank" href="ventPages/ventObj.html?' + v.id + '">' +
        '<strong>' + v.title + '</strong>' +
        '<div class="content"><div class="content-text">' + v.shortContent + '</div>' +
        '</a>' +
        '<div style="margin-top: 9px;">' +
        '<span>' +
        '<img class="like" width="18" height="18" alt="点赞数" src="staticFile/images/common/like.png"/>' + v.likeTotal +
        '</span>' +
        '<span>' +
        '<img width="16" height="16" src="staticFile/images/common/reply.png"/>' + v.commentTotal +
        '</span>' +
        '<span>' +
        '<img width="16" height="16" src="staticFile/images/common/city.png"/>' + v.cityName +
        '</span>' +
        '<span>' +
        '<' + aOrSpan + ' target="_blank" href="ventPages/hisHome.html?' + v.userId + '">' +
        '<img width="16" height="16" alt="吐槽人" src="staticFile/images/common/ventPeople.png"/>' + v.userNick +
        '</' + aOrSpan + '>' +
        '</span>' +
        '<span>' +
        '<img width="16" height="16" src="staticFile/images/common/vent16.png"/>' + v.occupationName +
        '</span>' +
        '<span>' +
        '<img width="16" height="16" src="staticFile/images/common/date.png"/>' + v.createDate.split('T')[0] +
        '</span>' +
        '</div>' +
        '</div>';
}
